package org.altervista.cp.microkernel;

import javax.sql.DataSource;

import org.altervista.cp.microkernel.util.ClassLoaderUtils;
import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.behaviors.Caching;

public interface KernelEngine {

	KernelEngine Instance = ClassLoaderUtils.getInstance(BootstrapProperties
			.getKernelEngineClassName(), new KernelEngine() {

		public <T> T addComponent(Class<T> c) {
			_container.addComponent(c);
			return _container.getComponent(c);
		}

		public boolean isInitialized() {
			return _initialized;
		}

		public boolean isStarted() {
			return _started;
		}

		public void setDataSource(DataSource ds) {
			_container.addComponent(ds);
			_initialized = true;
		}

		public void shutdown() {
			_started = false;
			_container.stop();
		}

		public void startup() {
			try {
				_container.addComponent(new WorkingDirectoryImpl());
				_container.addComponent(Class.forName(BootstrapProperties
						.getInstallManagerClassName()));
			} catch (ClassNotFoundException e) {
				throw new IllegalStateException(e);
			}
			_container.start();

			_started = true;
		}

		protected void finalize() {
			shutdown();
		}

		private MutablePicoContainer _container = new DefaultPicoContainer(
				new Caching());

		private boolean _initialized;
		private boolean _started;

	});

	<T> T addComponent(Class<T> c);

	boolean isInitialized();

	boolean isStarted();

	void setDataSource(DataSource ds);

	void shutdown();

	void startup();

}
